package com.dataseek.iot.auth.manager.web;

import com.dataseek.iot.auth.manager.service.CustomUserDetailsService;
import com.dataseek.iot.core.constant.ResponseConst;
import com.dataseek.iot.core.jwt.JwtTokenProvider;
import com.dataseek.iot.core.response.ResponseEntity;
import com.dataseek.iot.mysql.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;



/**
 * @author cc
 * @Title: 登陆
 * @Description: 登陆
 * @date 2021/9/89:08 下午
 * @since 1.0
 */
@RequestMapping("/auth")
@RestController
@Slf4j
@Api(tags = "登陆接口")
public class LoginController {

    @Autowired
    ReactiveAuthenticationManager authenticationManager;

    @Autowired
    JwtTokenProvider jwtTokenProvider;

    @Autowired
    CustomUserDetailsService customUserDetailsService;




    @PostMapping("/login")
    @ApiOperation("登陆")
    public Mono<Object> login(@RequestBody User user){
        //先做验证
        ResponseEntity response = customUserDetailsService.validate(user);
        if(response.getCode()!=ResponseConst.SUCCESS_CODE){
            return Mono.just(response);
        }
        Mono<Authentication> authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        return authentication.map(auth -> jwtTokenProvider.createToken(auth));
    }

    @GetMapping("/userDetails")
    @ApiOperation("获取用户详细信息")
    public Mono<ResponseEntity> userDetail(ServerWebExchange exchange){
        String bearerToken = exchange.getRequest().getHeaders().get("Authorization").get(0);
        log.info("权限信息为："+bearerToken);
        String token = null;
        String[] params = bearerToken.split(" ");
        if(params.length==3){
            token = params[2];
        }
        if(params.length==2){
            token  = params[1];
        }
        Authentication authentication = jwtTokenProvider.getAuthentication(token);
        return customUserDetailsService.userDetail(authentication);
    }

    @GetMapping("/logout")
    @ApiOperation("登出")
    public String logout(){
        return "logout";
    }


    @PostMapping("/validate")
    @ApiOperation("验证参数")
    public Mono<ResponseEntity> validate(@RequestBody User user){
       return Mono.just(customUserDetailsService.validate(user));
    }


}
